package org.example;


import org.example.mySwing.MyFrame;
import org.example.utils.MyMethod;

import java.io.File;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class Main {
    {
        rejectField.put("C:\\Program Files", 1);
        rejectField.put("C:\\Program Files (x86)", 1);
        rejectField.put("C:\\ProgramData", 1);
        rejectField.put("C:\\Windows", 1);
    }

    public final static int nThreads = File.listRoots().length + 10;

    private int maxInt = 10;
    //创建线程池
    public static ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    //    目标盘符 自己的移动盘
    public static String disc = getCurrentPath();
    //目标地址某盘+newFile文件夹下面
    public static String targetPath = disc + "newFile\\";

    public static ConcurrentLinkedQueue<File> pathQueue = new ConcurrentLinkedQueue<>();
    //    不查询的字段
    public static Map<String, Object> rejectField = new HashMap<>();
    //创建的线程方法
    MyMethod myMethod = new MyMethod();


    //初始化目标目录的文件夹
    public void init() {

        File file = new File(targetPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new RuntimeException("文件夹创建失败，请手动创建，盘根处名为newFile");
            }
        }
    }

    /**
     * 获取当前位置的移动盘
     */
    public static String getCurrentPath() {
        String currentDir = System.getProperty("user.dir");
        return currentDir.split("\\\\")[0] + "\\";
    }


    //单文件的复制
    public static void copy(File file) {
        try {
            //设置缓存大小 默认8kb
            ByteBuffer buffer = ByteBuffer.allocate(8192);
            String path = file.getPath();
            String[] splitName = path.split("\\\\");
            //名字+格式 例如 jdk1.8.0_131.zip
            String suffixName = splitName[splitName.length - 1];
            String[] suffix = suffixName.split("\\.");
            //文件格式 zip
            String suffixFormat = suffix[suffix.length - 1];
//            获得需要下载的文件的后缀
            StringBuffer suffixNum = MyFrame.suffixNum;
            File needFile = new File(targetPath + suffixFormat);
            if (!suffixNum.toString().contains(suffixFormat)||suffixFormat.length()<=1)return;
            if (!(needFile.exists())) needFile.mkdirs() ;
            MyFrame.textArea.append("正在下载："+path+"\n");
            Files.copy(Paths.get(path), Paths.get(targetPath+"\\"+suffixFormat+"\\"+ suffixName));
        } catch (Exception e) {
            handleException(e);
        }
    }

    private static void handleException(Exception e) {

        System.err.println("复制文件错误，有可能是权限不够，请用管理员权限运行：" + e.getMessage());
        // 记录日志或向外部组件报告异常信息
    }

    //更具输入的路径进行遍历盘符
    public void retrieval(File file) {
        ConcurrentLinkedQueue<File> pathQueueMin = new ConcurrentLinkedQueue<>();
        pathQueueMin.add(file);
        while (pathQueueMin.peek() != null) {
            File poll = pathQueueMin.poll();
            File[] files = poll.listFiles();
            if (!(files == null)) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        if (rejectField.get(file1.getPath()) == null) pathQueueMin.add(file1);
                    } else {
                        // 开启多个线程复制 由 myMethod 来控制线程开启的个数
                        executor.submit(() -> {
                            myMethod.threadCopy(file1);
                        });
                    }
                }
            }

        }
    }

    /**
     * 启动读和写
     *
     * @throws InterruptedException
     */
    public void startAll() {
        Main main = new Main();
        main.init();
        //开始遍历文件列表 全部盘一起遍历
        File[] files = File.listRoots();
        for (int i = 0; i < files.length; i++) {
            int finalI = i;
            if (files[i].getPath().contains(disc)) continue;
            executor.submit(() -> main.retrieval(files[finalI]));
        }
    }

    /**
     * 等待 检索队列内容 如果 9 秒后依然没内容就退出
     */
    public static File queueWait() {
        int sum = 0;
        File take = null;
        while ((take = pathQueue.poll()) == null) {
            mySleep(2000);
            sum++;
            if (sum == 3) {
                System.out.println("all stop");
                executor.shutdownNow();
                return null;
            }
        }
        return take;
    }


    /**
     * 线程等待 单位毫秒
     *
     * @param second 单位毫秒
     */
    public static void mySleep(int second) {
        try {
            Thread.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        Main startClass = new Main();
//        startClass.startAll();
        String str = "123" ;
        String str1 = "23" ;
        System.out.println(str.contains(str1));
    }
}